package com.itheima.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    private ObjectMapper objectMapper =new ObjectMapper();
    @Override

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Method method = null;
        try {
            //1.获取标记
            String pathInfo = req.getPathInfo().substring(1);//就是执行方法的名称
            //反射获取当前对象中要执行的方法对象method
            method = this.getClass().getDeclaredMethod(pathInfo, HttpServletRequest.class, HttpServletResponse.class);
            //开启访问权限
            method.setAccessible(true);
            //反射执行方法
            Object result = method.invoke(this, req, resp);//相当于CompanyServlet,findByPage(req,resp)
 /*
    定义响应json的方法,统一对客户端进行响应
     */
            objectMapper.writeValue(resp.getOutputStream(),result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
